/**
 * Radio Story Cards - using RFID tags to track physical story cards in an agile/lean environment.
 *
 * See http://www.radiostorycards.com for more information.
 *
 *
 * Copyright (C) 2011, Ted M. Young
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.radiostorycards.domain.cards;

import com.radiostorycards.domain.tags.RfidTag;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import java.util.List;

/**
 * Serializes/deserializes the state of a RadioCard to/from a string array for use with .CSV files.
 *
 * @author Ted Young <tedyoung@gmail.com> @JitterTed
 */
public class RadioCardDao {
  static final DateTimeFormatter DATE_TIME_FORMATTER = ISODateTimeFormat.dateTime();

  public static RadioCard fromRowOfCells(String[] cells) {
    int rfidTagId = Integer.parseInt(cells[0]);
    String jiraNumber = cells[1];
    RadioCard radioCard = RadioCard.createWithTag(new RfidTag(rfidTagId));
    radioCard.linkToJira(jiraNumber);

    int currentCell = 2;
    while (currentCell < cells.length - 1) {
      Column column = Column.valueOf(cells[currentCell++]);
      DateTime dateTime = DATE_TIME_FORMATTER.parseDateTime(cells[currentCell++]);
      radioCard.transitionTo(column, dateTime);
    }

    return radioCard;
  }

  public static String[] toRowOfCells(RadioCard radioCard) {
    List<CardState> cardStates = radioCard.getCardStates();
    String[] row = new String[2 + cardStates.size() * 2];
    row[0] = String.valueOf(radioCard.getRfidTag().hashCode());
    row[1] = radioCard.getJiraNumber();
    int currentCell = 2;
    for (CardState cardState : cardStates) {
      row[currentCell++] = cardState.getColumn().name();
      row[currentCell++] = DATE_TIME_FORMATTER.print(cardState.getDateTime());
    }
    return row;
  }
}
